import sys
import time
import hmac
import hashlib
import base64
import urllib.parse
import requests


def robot(string, location):
    timestamp = str(round(time.time() * 1000))
    # t = time.localtime()
    # date = f'{t.tm_hour:02}:{t.tm_min:02}'
    secret = ''
    if location == 'FZQ':
        secret = 'SECea02451ccd363388f015ffd538db7d25d8b5d6084d3c292a0947363a50b8bf2b'
    elif location == 'WHQ':
        secret = 'SEC9cecc2366ca1e3728625861c39ab71be4dfe1afccd71cdca2f8fd1ddd95f6943'
    elif location == 'PDQ':
        secret = 'SEC9bca698dc07f74709fe23c143a1b2b994b9ef89b4838882c525db9fe49aff953'
    secret_enc = secret.encode('utf-8')
    string_to_sign = f'{timestamp}\n{secret}'
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc,
                         digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    headers = {'Content-Type': 'application/json'}
    url = ''
    if location == 'FZQ':
        url = f'https://oapi.dingtalk.com/robot/send?access_token=a9ad3f9deb819d62a608fe5640a773f7bbc5aa2328aa4a06e858a0fbbfda8e4b&timestamp={timestamp}&sign={sign}'
    elif location == 'WHQ':
        url = f'https://oapi.dingtalk.com/robot/send?access_token=c88766070cf41652b80038f773f20a92bbc1b1439d1abc4602f946fa68ad89a3&timestamp={timestamp}&sign={sign}'
    elif location == 'PDQ':
        url = f'https://oapi.dingtalk.com/robot/send?access_token=f4532d8d1cc4a0f612293f77266e7c850532097c4d43b7b92a905c49d9ebc546&timestamp={timestamp}&sign={sign}'
    json={
            "msgtype": "text",
            "text": { "content": f"{string}" }
        }
    resp=requests.post(url=url,headers=headers,json=json)
    print(resp, file=sys.stderr)


if __name__ == "__main__":
    robot()
